package com.blogs.ui;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.blogs.component.HomeBaseActivity;
import com.blogs.entity.AppConfig;
import com.blogs.entity.AppEnums;
import com.blogs.entity.VerSion;
import com.blogs.service.CheckVersionTask;
import com.blogs.service.CheckVersionTask.IMsgCallBack;
import com.blogs.tools.DBClear;
import com.blogs.tools.DBSharedPreferences;
import com.blogs.tools.IO;
import com.blogs.tools.Tools;
import com.cnblogs.R;

public class SettingActivity extends HomeBaseActivity implements OnClickListener, OnSeekBarChangeListener {
	private TextView title_include_title;
	private DBSharedPreferences sp;

	private RelativeLayout setting_drafts_ll;
	private RelativeLayout setting_com_queue_ll;
	private RelativeLayout setting_offline_dwn_ll;
	private RelativeLayout setting_show_pic_ll;
	private RelativeLayout setting_clear_cache_ll;
	private RelativeLayout setting_full_screen_ll;
	private RelativeLayout setting_dark_state_ll;
	private RelativeLayout setting_set_textsize_ll;

	private RelativeLayout setting_about_rl;
	private RelativeLayout setting_evaluate_rl;
	private RelativeLayout setting_share_rl;
	private RelativeLayout setting_update_rl;
	private RelativeLayout setting_shutdown_rl;
	private RelativeLayout setting_feedback_rl;

	private LinearLayout setting_root;
	private LinearLayout setting_group_1;
	private LinearLayout setting_group_2;
	private ImageView setting_showpic_iv;
	private ImageView setting_full_screen_iv;
	private ImageView setting_dark_state_iv;
	private Toast toast;

	private RelativeLayout title_top_bg;

	private ProgressDialog dialog;
	private AlertDialog.Builder exitDialog;
	private AlertDialog.Builder delCache;

	private LayoutInflater mInflater;
	private View text_size_view;
	private SeekBar seekBar_fontsize;
	private int newProgress = 0;
	private int curTextSize;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting);
		ViewGroup headview = (ViewGroup) findViewById(R.id.main_title_include);
		title_include_title = (TextView) headview.findViewById(R.id.title_include_title);
		title_include_title.setText("设置");
		title_top_bg = (RelativeLayout) headview;
		setting_root = (LinearLayout) findViewById(R.id.setting_root);
		setting_group_1 = (LinearLayout) findViewById(R.id.setting_group_1);
		setting_group_2 = (LinearLayout) findViewById(R.id.setting_group_2);
		sp = new DBSharedPreferences(this);

		setting_drafts_ll = (RelativeLayout) findViewById(R.id.setting_drafts_ll);
		setting_com_queue_ll = (RelativeLayout) findViewById(R.id.setting_com_queue_ll);
		setting_offline_dwn_ll = (RelativeLayout) findViewById(R.id.setting_offline_dwn_ll);
		setting_show_pic_ll = (RelativeLayout) findViewById(R.id.setting_show_pic_ll);
		setting_clear_cache_ll = (RelativeLayout) findViewById(R.id.setting_clear_cache_ll);
		setting_dark_state_ll = (RelativeLayout) findViewById(R.id.setting_dark_state_ll);
		setting_full_screen_ll = (RelativeLayout) findViewById(R.id.setting_full_screen_ll);
		setting_set_textsize_ll = (RelativeLayout) findViewById(R.id.setting_set_textsize_ll);

		setting_about_rl = (RelativeLayout) findViewById(R.id.setting_about_rl);
		setting_evaluate_rl = (RelativeLayout) findViewById(R.id.setting_evaluate_rl);
		setting_share_rl = (RelativeLayout) findViewById(R.id.setting_share_rl);
		setting_update_rl = (RelativeLayout) findViewById(R.id.setting_update_rl);
		setting_shutdown_rl = (RelativeLayout) findViewById(R.id.setting_shutdown_rl);
		setting_feedback_rl = (RelativeLayout) findViewById(R.id.setting_feedback_rl);

		setting_showpic_iv = (ImageView) findViewById(R.id.setting_showpic_iv);
		if (sp.GetIsShowPic()) {
			setting_showpic_iv.setImageResource(R.drawable.switch_on);
		} else {
			setting_showpic_iv.setImageResource(R.drawable.switch_off);
		}
		setting_full_screen_iv = (ImageView) findViewById(R.id.setting_full_screen_iv);
		if (sp.GetIsFullScreen()) {
			setting_full_screen_iv.setImageResource(R.drawable.switch_on);
		} else {
			setting_full_screen_iv.setImageResource(R.drawable.switch_off);
		}
		setting_dark_state_iv = (ImageView) findViewById(R.id.setting_dark_state_iv);
		if (sp.GetIsDarkState()) {
			setting_dark_state_iv.setImageResource(R.drawable.switch_on);
		} else {
			setting_dark_state_iv.setImageResource(R.drawable.switch_off);
		}
		InitSkin();
		setting_drafts_ll.setOnClickListener(this);
		setting_com_queue_ll.setOnClickListener(this);
		setting_offline_dwn_ll.setOnClickListener(this);
		setting_show_pic_ll.setOnClickListener(this);
		setting_clear_cache_ll.setOnClickListener(this);
		setting_dark_state_ll.setOnClickListener(this);
		setting_full_screen_ll.setOnClickListener(this);
		setting_set_textsize_ll.setOnClickListener(this);

		setting_about_rl.setOnClickListener(this);
		setting_evaluate_rl.setOnClickListener(this);
		setting_share_rl.setOnClickListener(this);
		setting_update_rl.setOnClickListener(this);
		setting_feedback_rl.setOnClickListener(this);
		setting_shutdown_rl.setOnClickListener(this);

		initDialog();
	}

	private void InitSkin() {
		if (sp.GetIsDarkState()) {
			title_top_bg.getBackground().setLevel(2);
			setting_root.getBackground().setLevel(2);
			 setting_group_1.getBackground().setLevel(2);
			 setting_group_2.getBackground().setLevel(2);
		} else {
			title_top_bg.getBackground().setLevel(1);
			setting_root.getBackground().setLevel(1);
			setting_group_1.getBackground().setLevel(1);
			setting_group_2.getBackground().setLevel(1);
		}
	}

	private void initDialog() {
		dialog = new ProgressDialog(this);
		dialog.setIndeterminate(true);
		dialog.setMessage("正在检查更新");

		exitDialog = new AlertDialog.Builder(this).setIcon(R.drawable.icon).setTitle("确认退出?")
				.setPositiveButton("确认", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						finish();
					}
				}).setNegativeButton("取消", null);

		delCache = new AlertDialog.Builder(this).setIcon(R.drawable.icon).setTitle("是否清除缓存?")
				.setMessage("清除缓存后离线下载文章将会被删除,是否确定要清除?")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						clearThread mthread = new clearThread();
						mthread.start();
						showToast("正在清除缓存");
					}
				}).setNegativeButton("取消", null);
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == setting_drafts_ll) {

			Intent intent = new Intent();
			intent.setClass(SettingActivity.this, BlogDraftActivity.class);
			startActivity(intent);
		} else if (v == setting_com_queue_ll) {
			Intent intent = new Intent();
			intent.setClass(SettingActivity.this, CommentQueueActivity.class);
			startActivity(intent);
		} else if (v == setting_offline_dwn_ll) {
			Intent intent = new Intent();
			intent.setClass(SettingActivity.this, OfflineDownloadActivity.class);
			startActivity(intent);
		} else if (v == setting_shutdown_rl) {
			exitDialog.show();
		} else if (v == setting_clear_cache_ll) {
			delCache.show();
		} else if (v == setting_show_pic_ll) {
			if (sp.GetIsShowPic()) {
				setting_showpic_iv.setImageResource(R.drawable.switch_off);
			} else {
				setting_showpic_iv.setImageResource(R.drawable.switch_on);
			}
			sp.SetIsShowPic(!sp.GetIsShowPic());
		} else if (v == setting_dark_state_ll) {
			// 夜间模式
			if (sp.GetIsDarkState()) {
				setting_dark_state_iv.setImageResource(R.drawable.switch_off);
			} else {
				setting_dark_state_iv.setImageResource(R.drawable.switch_on);
			}
			sp.SetIsDarkState(!sp.GetIsDarkState());
			InitSkin();
			Intent intent = new Intent("SkinChangeReceiver");
			sendBroadcast(intent);
		} else if (v == setting_set_textsize_ll) {

			mInflater = getLayoutInflater();
			text_size_view = mInflater.inflate(R.layout.text_size_view, null);
			seekBar_fontsize = (SeekBar) text_size_view.findViewById(R.id.seekBar_fontsize);
			new AlertDialog.Builder(SettingActivity.this).setIcon(R.drawable.icon).setTitle("设置正文字体大小")
					.setView(text_size_view).setPositiveButton("确定", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							sp.SetTextSize(curTextSize);
						}
					}).setNegativeButton("取消", null).show();
			seekBar_fontsize.setMax(100);
			seekBar_fontsize.setOnSeekBarChangeListener(this);
			// lastProgress=? 从配置文件中读取
			int curp;
			curTextSize = sp.GetTextSize();
			if (curTextSize == AppConfig.TEXT_SIZE_SMALL) {
				curp = 0;
			} else if (curTextSize == AppConfig.TEXT_SIZE_MIDDLE) {
				curp = 50;
			} else {
				curp = 100;
			}

			seekBar_fontsize.setProgress(curp);
		} else if (v == setting_full_screen_ll) {
			Intent intent = new Intent("ChangeScreenState");
			if (sp.GetIsFullScreen()) {
				setting_full_screen_iv.setImageResource(R.drawable.switch_off);
				intent.putExtra("state", AppEnums.ScreenState.None);
			} else {
				setting_full_screen_iv.setImageResource(R.drawable.switch_on);
				intent.putExtra("state", AppEnums.ScreenState.Full);
			}
			sp.SetIsFullScreen(!sp.GetIsFullScreen());
			sendBroadcast(intent);

		} else if (v == setting_update_rl) {
			dialog.show();
			new CheckVersionTask(this, new IMsgCallBack() {

				public void onSuccess(VerSion vs) {
					// TODO Auto-generated method stub
					if (vs.has_new_version.equals("1")) {
						Intent intent = new Intent();
						intent.setClass(SettingActivity.this, VersionUpdateActivity.class);
						intent.putExtra("version_text", vs.version_text);
						intent.putExtra("version_introduction", vs.version_introduction);
						intent.putExtra("file_path", vs.file_path);
						startActivity(intent);
					} else {
						showToast("暂无新版本");
					}
					dialog.hide();
				}

				public void onFailed() {
					// TODO Auto-generated method stub
					dialog.hide();
					showToast("暂无新版本");
				}
			}).GetResult();
		} else if (v == setting_about_rl) {
			Intent intent = new Intent();
			intent.setClass(SettingActivity.this, AboutActivity.class);
			startActivity(intent);
		} else if (v == setting_evaluate_rl) {
			try {
				Uri uri = Uri.parse("market://details?id=" + Tools.GetPackageInfo(this).packageName);
				Intent it = new Intent(Intent.ACTION_VIEW, uri);
				it.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
				startActivity(it);
			} catch (Exception e) {
				Toast.makeText(SettingActivity.this, "您的机子里没有安装安卓市场", Toast.LENGTH_SHORT).show();
			}
		} else if (v == setting_share_rl) {
			Intent intent = new Intent(Intent.ACTION_SEND); // 启动分享发送的属性
			intent.setType("text/plain"); // 分享发送的数据类型
			intent.putExtra(Intent.EXTRA_SUBJECT, "博客园安卓客户端"); // 分享的主题
			intent.putExtra(Intent.EXTRA_TEXT, "博客园安卓客户端很不错,你也装一个来玩玩吧http://apk.gfan.com/Product/App364776.html"); // 分享的内容
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 这个也许是分享列表的背景吧
			SettingActivity.this.startActivity(Intent.createChooser(intent, "分享博客园安卓客户端"));// 目标应用选择对话框的标题
		} else if (v == setting_feedback_rl) {
			Intent intent = new Intent();
			intent.setClass(SettingActivity.this, FeedBackActivity.class);
			startActivity(intent);

		}
	}

	public void onProgressChanged(SeekBar paramSeekBar, int progress, boolean fromUser) {
		Log.i("newProgress", newProgress + "");
		newProgress = progress;
	}

	public void onStartTrackingTouch(SeekBar paramSeekBar) {

	}

	public void onStopTrackingTouch(SeekBar paramSeekBar) {

		if (newProgress < 30) {
			newProgress = 0;
			curTextSize = AppConfig.TEXT_SIZE_SMALL;
			paramSeekBar.setProgress(0);
		} else if (newProgress > 70) {
			// 设置lastProgress 要放在setProgress之前，否则可能导致执行多次onProgressChanged 改变了原值
			newProgress = 100;
			curTextSize = AppConfig.TEXT_SIZE_BIG;
			paramSeekBar.setProgress(100);
		} else {
			newProgress = 50;
			curTextSize = AppConfig.TEXT_SIZE_MIDDLE;
			paramSeekBar.setProgress(50);
		}
	}

	private void showToast(String text) {
		if (toast == null) {
			toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
		} else {
			toast.setText(text);
			toast.setDuration(Toast.LENGTH_SHORT);
		}
		toast.show();
	}

	private class clearThread extends Thread {
		@Override
		public void run() {
			DBClear dbclear = new DBClear(SettingActivity.this);
			dbclear.Clear();
			dbclear.DbClose();
			String path = "/sdcard/" + AppConfig.SD_CARD_FOLDER + "/";
			try {
				IO.del(path);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Message msg = new Message();
			msg.what = 1;
			myhandler.sendMessage(msg);
		}
	}

	Handler myhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if (msg.what == 1) {
				showToast("清除缓存成功");
			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		dialog.dismiss();
	}
}
